package com.ververica.cdc.guass.sink.jdbc.internal;

import com.ververica.cdc.common.annotation.Internal;
import org.apache.flink.api.common.typeutils.TypeSerializer;

import java.io.Serializable;

/** A Serializer that have in account the actual configuration. */
@Internal
public class JdbcOutputSerializer<T> implements Serializable {

    private final TypeSerializer<T> typeSerializer;
    private boolean objectReuse;

    private JdbcOutputSerializer(TypeSerializer<T> typeSerializer, boolean objectReuse) {
        this.typeSerializer = typeSerializer;
        this.objectReuse = objectReuse;
    }

    public static <S> JdbcOutputSerializer<S> of(TypeSerializer<S> typeSerializer) {
        return of(typeSerializer, false);
    }

    public static <S> JdbcOutputSerializer<S> of(
            TypeSerializer<S> typeSerializer, boolean objectReuse) {
        return new JdbcOutputSerializer<>(typeSerializer, objectReuse);
    }

    public JdbcOutputSerializer<T> withObjectReuseEnabled(boolean enabled) {
        this.objectReuse = enabled;
        return this;
    }

    public T serialize(T record) {
        return this.objectReuse ? typeSerializer.copy(record) : record;
    }
}
